<?php

namespace app\admin\service;

use app\model\Partners;
use app\model\Videos;
use app\model\WatchPayRecord;
use app\model\MonetaryStatistics;

class TaskService
{
    private $partnersModel;
    private $videosModel;
    private $watchPayRecordModel;
    private $monetaryStatisticsModel;

    public function __construct(Partners $partnersModel, Videos $videosModel, WatchPayRecord $watchPayRecordModel, MonetaryStatistics $monetaryStatisticsModel)
    {
        $this->partnersModel = $partnersModel;
        $this->videosModel = $videosModel;
        $this->watchPayRecordModel = $watchPayRecordModel;
        $this->monetaryStatisticsModel = $monetaryStatisticsModel;
    }

    // 统计每个版权输入合作方每天的消费金额
    public function monetaryStatistics()
    {
        $date = date('Ymd', strtotime('-1 day'));
        $month = date('Ym', strtotime('-1 day'));
        $time = strtotime('-1 day');

        // 获取输入合作方
        $where = [
            ['type', '=', 1],
            ['status', '=', 1],
            ['start_time', '<', $time],
            ['end_time', '>', $time]
        ];
        $data = $this->partnersModel->getDataByWhere($where, 'id, abbreviation as name');
        $ids = array_column($data, 'id');

        // 获取合作方的短剧
        $videoData = $this->videosModel->getDataByWhere(['partners_id' => $ids], 'id, partners_id, cooperation_mode, scale');
        $videoIds = array_column($videoData, 'id');

        // 获取短剧今天的消费数据
        $watchPayData = $this->watchPayRecordModel->getInfo(['video_id' => $videoIds, 'consume_date' => $date], 'video_id, money');
        $watchPayResult = [];
        foreach ($watchPayData as $item) {
            $watchPayResult[$item['video_id']][] = $item['money'];
        }

        $result = [];
        foreach ($videoData as $key => $item) {
            $consumeMoney = empty($watchPayResult[$item['id']]) ? 0 : array_sum($watchPayResult[$item['id']]);
            $item['consume_money'] = round($consumeMoney / 100, 2);
            $item['divided_amount'] = round($consumeMoney / 100 * $item['scale'] / 100, 2);
            $result[$item['partners_id']][] = $item;
        }

        $saveData = [];
        foreach ($data as $key => $item) {

            $monetary = $dividedAmount = 0;
            foreach ($result[$item['id']] as $value) {
                $monetary += $value['consume_money'];
                $dividedAmount += $value['divided_amount'];
            }

            $saveData[] = [
                'partners_id' => $item['id'],
                'name' => $item['name'],
                'monetary' => $monetary,
                'divided_amount' => $dividedAmount,
                'month' => intval($month),
                'date' => intval($date),
                'created_at' => time()
            ];
        }

        $this->monetaryStatisticsModel->saveAll($saveData);

        return true;
    }
}